package com.hmall.common.config.mq;

import com.hmall.common.utils.MqHelper;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * <p>
 * RabbitMQ消息转换器配置
 * <p>
 * @author: liuhongjun
 * @since: 2024-05-16
 */
@Slf4j
@Configuration
public class MqConfig {

    @Bean
    public MessageConverter messageConverter() {
        // 1.定义消息转换器
        Jackson2JsonMessageConverter jackson2JsonMessageConverter = new Jackson2JsonMessageConverter();
        // 2.配置自动创建消息id，用于识别不同消息，也可以在业务中基于ID判断是否是重复消息
        jackson2JsonMessageConverter.setCreateMessageIds(true);
        return jackson2JsonMessageConverter;
    }

    @Bean
    public MqHelper rabbitMqHelper(RabbitTemplate rabbitTemplate) {
        return new MqHelper(rabbitTemplate);
    }

    //@Bean
    public ChannelAwareMessageListener channelAwareMessageListener() {
        return new ChannelAwareMessageListener() {
            @Override
            public void onMessage(Message message, Channel channel) {
                MessageProperties properties = message.getMessageProperties();
                Long userId = properties.getHeader("user-info");
                log.info("用户id信息：{}", userId);
            }
        };
    }

}
